<route lang="jsonc" type="page">
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "登录"
  }
}
</route>

<script lang="ts" setup>
import { useTokenStore } from '@/store/token'
import { useUserStore } from '@/store/user'
import { tabbarList } from '@/tabbar/config'
import { isPageTabbar } from '@/tabbar/store'
import { ensureDecodeURIComponent } from '@/utils'
import { parseUrlToObj } from '@/utils/index'

const redirectUrl = ref('')
onLoad((options) => {
  console.log('login options: ', options)
  if (options.redirect) {
    redirectUrl.value = ensureDecodeURIComponent(options.redirect)
  }
  else {
    redirectUrl.value = tabbarList[0].pagePath
  }
  console.log('redirectUrl.value: ', redirectUrl.value)
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
const isWechatMini = ref(false)
const isLoading = ref(false)

// 检测是否为微信小程序环境
// #ifdef MP-WEIXIN
isWechatMini.value = true
// #endif

// 模拟登录（非微信小程序环境）
function doLogin() {
  userStore.setUserInfo({
    userId: 123456,
    username: 'abc123456',
    nickname: '菲鸽',
    avatar: 'https://oss.laf.run/ukw0y1-site/avatar.jpg',
  })
  navigateToRedirect()
}

// 微信小程序登录
async function doWechatLogin() {
  if (isLoading.value)
    return

  isLoading.value = true
  try {
    await tokenStore.wxLogin()
    navigateToRedirect()
  }
  catch (error) {
    console.error('微信登录失败:', error)
    // token store 已经显示了错误提示，这里不重复显示
  }
  finally {
    isLoading.value = false
  }
}

// 导航到重定向页面
function navigateToRedirect() {
  console.log(redirectUrl.value)
  let path = redirectUrl.value
  if (!path.startsWith('/')) {
    path = `/${path}`
  }
  const { path: _path, query } = parseUrlToObj(path)
  console.log('_path:', _path, 'query:', query, 'path:', path)
  console.log('isPageTabbar(_path):', isPageTabbar(_path))

  if (isPageTabbar(_path)) {
    uni.switchTab({
      url: path,
    })
  }
  else {
    console.log('redirectTo:', path)
    uni.redirectTo({
      url: path,
    })
  }
}
</script>

<template>
  <view class="login">
    <view class="login-container">
      <view class="logo-section">
        <image class="logo" src="/static/logo.svg" mode="aspectFit" />
        <text class="app-name">LuckCoder</text>
        <text class="app-desc">示例项目</text>
      </view>

      <view class="login-section">
        <!-- 微信小程序环境 -->
        <template v-if="isWechatMini">
          <button
            class="wechat-login-btn"
            :disabled="isLoading"
            @click="doWechatLogin"
          >
            <view class="btn-content">
              <uni-icons v-if="!isLoading" type="weixin" size="20" color="#ffffff" />
              <text v-if="isLoading">登录中...</text>
              <text v-else>微信授权登录</text>
            </view>
          </button>
        </template>

        <!-- 非微信小程序环境 -->
        <template v-else>
          <view class="mb-4 text-center">
            <text class="text-gray-600">本页面主要用于 H5 和 APP</text>
          </view>
          <button class="demo-login-btn" @click="doLogin">
            点击模拟登录
          </button>
        </template>
      </view>

      <view class="footer-section">
        <text class="footer-text">登录即表示同意服务条款和隐私政策</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.login {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.login-container {
  width: 100%;
  max-width: 600rpx;
  background: white;
  border-radius: 20rpx;
  padding: 80rpx 60rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.1);
}

.logo-section {
  text-align: center;
  margin-bottom: 80rpx;

  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 20rpx;
  }

  .app-name {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .app-desc {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.login-section {
  margin-bottom: 60rpx;
}

.wechat-login-btn {
  width: 100%;
  height: 88rpx;
  background: #07c160;
  border: none;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;

  &:disabled {
    background: #9ed99d;
  }

  .btn-content {
    display: flex;
    align-items: center;
    gap: 16rpx;

    text {
      color: white;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
}

.demo-login-btn {
  width: 100%;
  height: 88rpx;
  background: #667eea;
  border: none;
  border-radius: 44rpx;
  color: white;
  font-size: 32rpx;
  font-weight: 500;
  margin-top: 20rpx;
}

.footer-section {
  text-align: center;

  .footer-text {
    font-size: 24rpx;
    color: #999;
    line-height: 1.5;
  }
}

.text-center {
  text-align: center;
}

.mb-4 {
  margin-bottom: 32rpx;
}

.text-gray-600 {
  color: #6b7280;
}
</style>
